/************常量定义区域**********************/
/** AJAX请求超时时间 */
var ajaxCommonTimeout = 60000;

/** 视频相关定义 */
var VIDEO_SUFFIX = ".webm"; // 视频后缀常量
var VIDEO_POSTER_SUFFIX = ".jpg"; // 视频预览图片后缀常量

/**
 * 素材类型枚举定义
 */
var MaterialTypeEnum = {
    IMAGE: 1,
    TEXT: 2,
    WEB: 3,
    VIDEO: 4,
    RECORD: 5
};

/**
 * 分析类型枚举定义
 */
var AnalysisTypeEnum = {
    HEATMAP: "heatmap",
    ROUTEMAP: "routemap",
    FOCUSMAP: "focusmap",
    GRIDMAP: "gridmap",
    AOI: "interestarea",
    STATISTIC: "statistic"
};

/** ************************************** */

$(document).ready(function () {
    // 取消a标签点击默认事件，即点击后不跳到页面顶部
    $("a[href='#']").click(function (event) {
        event.preventDefault();
    });
    // 页面顶部导航栏为最后一个span增加last样式，便于不在后面显示导航箭头
    $(".plat>span:last").addClass("last");
    // 窗口大小改变时调用setContentH，便于重新设置Content容器高度
    $(window).resize(function () {
        setContentH();
    });

    setContentH(); // 初始化内容区域高度，使其最小高度为显示区域高度减去头部菜单和底部
    initForm(); // 初始化表单
    initDatagrid(); // 初始化表格样式
    tab_nextChange();
});

function setContentH() {
    var min = window.min_height || 0;
    var hh = document.documentElement.clientHeight || document.body.clientHeight; // 浏览器内容窗口高度
    var headH = $(".head").outerHeight(true);
    var footerH = $(".footer").outerHeight(true);
    var minHeight = hh - headH - footerH;
    if (min > 0 && min <= minHeight) {
        return;
    }
    window.min_height = minHeight;
    if ($(".content").length > 0) { // 内容区域最小高度为屏幕高度
        $(".content")[0].style.minHeight = minHeight + "px";
    }
    if ($(".content .fixedH")) { // 内容区域左右两栏固定等高
        var toolbarH = $(".toolbar").outerHeight(true);
        minHeight = minHeight > 450 ? minHeight : 450;
        $(".fixedH>div").height(minHeight - toolbarH);
    }
}

function initDatagrid() {
    // dataGrid列表奇偶行样式
    $(".dataGrid tbody").find("tr:odd").addClass("odd");
    $(".dataGrid tbody").find("tr:even").removeClass("odd");
    // 列表行鼠标移入样式
    $(".tableHover").find("tr").hover(function () {
        $(this).addClass("trHover");
    }, function () {
        $(this).removeClass("trHover");
    });
    // dataGrid列表和widget元素内表格最后一行加上last样式名以去掉边线
    $(".dataGrid,.widget").find("tr").find("td:last").addClass("last");
    DGCheckboxCtrl();// 初始化复选按钮勾选后 行样式
}

/**
 * 列表头复选全选功能
 */
function initDatagrid_click() {
    /* 列表复选框全选功能 */

    // 表头checkbox
    $(".dataGrid thead :input,.dataList thead :input").click(function (event) {
        event.stopPropagation();
        var itemChk = $(this).closest("table").find("tbody :input").not(":disabled,:hidden");
        itemChk.attr("checked", this.checked);
        DGCheckboxCtrl();
    });
    // tbody checkbox
    $(".dataGrid tbody :checkbox,.dataList tbody :input").click(function (event) {
        event.stopPropagation();
        tbodyCkClick($(this));
    });
    $(".dataGrid tbody tr,.dataList tbody tr").click(function () {
        var this_tr = $(this), this_ck = this_tr.find("td>input");
        if (this_ck.length > 0) {
            this_ck.attr("checked", !this_ck[0].checked);
            tbodyCkClick(this_ck);
            this_ck.trigger("change");
        }
    });

    function tbodyCkClick(obj) {
        var $tmp = $(obj).closest("tbody").find("input").not(":disabled,:hidden");
        var checked = $tmp.length == $tmp.filter('input:checked').not(":disabled,:hidden").length;
        $(obj).closest("table").find("thead input").attr('checked', checked);
        DGCheckboxCtrl();
    }

    // 列表复选框勾选后增加样式
    $(".dataGrid input:checkbox,.dataList input").click(function () {
        checkedStyle($(this));
    });
}

function DGCheckboxCtrl() {
    $(".dataGrid tbody input").parents("tr").removeClass("on");
    $(".dataGrid tbody :checked").parents("tr").addClass("on");
}

function checkedStyle(obj) {
    var this_ = $(obj);
    if (!this_.attr("checked")) {
        this_.closest("tr").removeClass("on");
    } else if (this_.attr("checked")) {
        this_.closest("tr").addClass("on");
    }
}

function initForm() {// 输入框聚焦效果
    try {
        $("textarea,.inputText,:password,:file").focus(function () {
            var rd = $(this).attr("readonly") || $(this).attr("disabled");
            if (!rd) {
                $(this).addClass("onFocus");
                return false;
            }
        }).blur(function () {
            $(this).removeClass("onFocus");
        });
    } catch (e) {
    }
}

// 占位符提示
function inputTip(t, tVal) {
    t.val(tVal);
    if (t.val() == tVal) {
        t.css("color", "#aaaaaa")
    }
    t.focus(function () {
        if ($(this).val() == tVal) {
            $(this).val("");
            $(this).css("color", "#555555");
        }
    }).blur(function () {
        if ($(this).val() == "") {
            $(this).val(tVal);
            $(this).css("color", "#aaaaaa")
        } else {
            $(this).css("color", "#555");
        }
    })
}

// 弹出窗口
function popalert(parameter) {
    var content = parameter.content, icon = parameter.icon ? parameter.icon : 'question',
        okVal = parameter.okVal ? parameter.okVal : '确定', cancelVal = parameter.cancelVal ? parameter.cancelVal
        : '取消', ok = parameter.ok, cancel = parameter.cancel, close = parameter.close;
    art.dialog({
        content: content,
        icon: icon,
        fixed: true,
        lock: true,
        ok: function () {
            eval(ok);
        },
        okVal: okVal,
        cancel: cancel,
        cancelVal: cancelVal,
        path: '../js/artDialog4.1.7',
        close: function () {
            eval(close);
        }
    });
}

function popup(title, url, w, h, id, lock) {
    var hh = top.window.document.documentElement.clientHeight || document.body.clientHeight;
    hh = hh - 45;
    if (hh < h) {
        h = hh;
    }
    if (lock == undefined) {
        lock = true;
    }
    top.art.dialog.open(url, {
        id: id,
        title: title,
        width: w,
        height: h,
        top: 50,
        padding: 0,
        lock: true
    });
    if (/(chooseTransformer\.html)/g.test(url)) {
        top['chooseTransformerParentWindow'] = window;
    }
}

// 关闭弹出窗口
function popdown(id) {
    top.artDialog({
        id: id
    }).close();
}

/* ===tab_nex点击切换内容DIV隐藏显示=== */
function tab_nextChange() {
    if ($(".tab_next_con").length > 0) {
        tabContentShow();
        $(".tab_next li").not(".noAction").bind("click", function () {
            $(this).closest(".tab_next").find(".on").removeClass('on');
            $(this).addClass("on");
            tabContentShow();
        });
    }
}

function tabContentShow() {
    $(".tab_next_con > div").hide();
    $(".tab_next .on").each(function () {
        var id = $(this).attr("id") + "_c";
        $("#" + id).show();
    });
}

// 文字截取
function ellipsis(obj, maxwidth) {
    $(obj).each(function () {
        if (maxwidth == undefined) {
            var max = 25;
        } else {
            var max = maxwidth;
        }
        var thisText = $.trim($(this).text()); // 去空格
        if (thisText.length > max) {
            $(this).text(thisText.substring(0, max));
            $(this).html($(this).html() + '...');
        }
    });
}

/* ===msg tips 成功失败提示信息=== */
(function (tips) {
    var mm = 3
    DOT = ".", CSS = {
        MSG: 'msg',
        TIME: 'msg_time'
    }, Tmpl = {
        FALSE: ['<div class="msg false">', '<dl>', '<dt>很遗憾，操作失败。</dt>', '<dd class="msg_time">', '<span></span>秒钟后，自动关闭，您也可以手动<a href="#">关闭</a>', '</dd>', '</dl>', '</div>'].join(''),
        SUCCESS: ['<div class="msg success">', '<dl>', '<dt>恭喜您，操作成功。</dt>', '<dd class="msg_time">', '<span></span>秒钟后，自动关闭，您也可以手动<a href="#">关闭</a>', '</dd>', '</dl>', '</div>'].join('')
    };

    function msg(parameter) {
        var type = parameter.type, text = parameter.text, obj = parameter.follow;
        callFn = parameter.callFn;

        showMsg(type, text);
        location(obj);
        $(DOT + CSS.TIME).find("a").click(function () {
            $(DOT + CSS.MSG).hide();
            clearTimeout(t);
        });
        show_date_time();
    }

    function showMsg(msgType, text) {
        var msg, msgTip;
        if (msgType == "false") {
            msg = Tmpl.FALSE;
            msgTip = $(".false");
        } else {
            msg = Tmpl.SUCCESS;
            msgTip = $(".success");
        }
        if (msgTip.length > 0) {
            $(DOT + CSS.MSG).hide();
            clearTimeout(t);
            msgTip.show();
        } else {
            $("body").append(msg);
        }
        if (text) {
            $(".msg:visible").find("dt").html(text);
        }
        mm = 3;
    }

    function show_date_time() {
        if (mm > 0) {
            t = window.setTimeout(function () {
                show_date_time();
            }, 1000);
        } else {
            $(DOT + CSS.MSG).hide();
            if (callFn) {
                callFn();
            }
        }
        $(DOT + CSS.TIME).find(">span").text(mm);
        mm--;
    }

    function location(obj) {
        var btn;
        if (obj == undefined) {
            btn = $(".editBlock tr:last .inputButton");
        } else {
            btn = $(obj);
        }
        var msgH = $(DOT + CSS.MSG).filter(":visible").outerHeight(true);
        var left = btn.offset().left;
        var top = btn.offset().top - msgH - 15;
        $(DOT + CSS.MSG).css({
            "left": left,
            "top": top
        });
    }

    tips.msg = msg;
})(window);

/**
 * 格式化毫秒数时间,HH:mm:ss
 */
function formatMilliSeconds(value) {
    value = value / 1000;
    var theTime = parseInt(value);// 秒
    var theTime1 = 0;// 分
    var theTime2 = 0;// 小时
    // alert(theTime);
    if (theTime > 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        // alert(theTime1+"-"+theTime);
        if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
        }
    }
    var result = "";
    if (theTime2 < 0) {
        result = "00:";
    } else if (theTime2 < 10) {
        result = "0" + parseInt(theTime2) + ":";
    } else {
        result = parseInt(theTime2) + ":";
    }

    if (theTime1 < 0) {
        result += "00:";
    } else if (theTime1 < 10) {
        result += "0" + parseInt(theTime1) + ":";
    } else {
        result += parseInt(theTime1) + ":";
    }

    if (theTime < 0) {
        result += "00";
    } else if (theTime < 10) {
        result += "0" + parseInt(theTime);
    } else {
        result += parseInt(theTime);
    }

    return result;
}

function loading() {
    var hasNext = window.hasOpenLoading == null ? true : window.hasOpenLoading;
    if (hasNext) {
        loadShow(true);
    }
}

function closeLoad() {
    var hasNext = window.hasOpenLoading == null ? true : window.hasOpenLoading;
    if (hasNext) {
        loadShow(false);
    }
}

function loadShow(force) {
    if (force) {
        var load = ['<div class="loadBg"></div>'].join("");
        if ($(".loadBg").length <= 0) {
            $("body").append(load);
        }
        $(".loadBg").show();
    } else {
        $(".loadBg").hide();
    }
}

function ajaxLoading(jqObj, url, params, handler) {
    // 设置AJAX请求超时时间
    $.ajaxSetup({
        timeout: ajaxCommonTimeout
    });
    jqObj.load(url, params, function (response, status, xhr) {
        handler(status);
    });
}

/**
 * 加载进度条
 *
 * @param percent
 */
var DownLoading = function () {
};

DownLoading.prototype = {
    timer: null,
    percent: 0,
    maxPercent: 0,
    config: {
        size: 100,
        enlarge: 1.8,
        speed: 200,
        orange: 30,
        yellow: 55,
        green: 85
    },
    getMe: function () {
        return $('.down-load-all');
    },
    start: function (percent) {
        this.getMe().remove();
        var _htm = '<div class="down-load-all">';
        _htm += '<div class="loading-progress loading-progress-active"><div class="loading-progress-bar">';
        _htm += '<span class="loading-progress-text">数据分析中，请稍候...(<em>0%</em>)</span>';
        _htm += '</div></div></div>';
        $('body').prepend(_htm);
        return this.append(percent);
    },
    load: function () {
        var me = this;
        var config = me.config;
        var percent = me.percent;
        var $progress = me.getMe().find('.loading-progress');
        var $bar = me.getMe().find('.loading-progress-bar');
        var $txt = me.getMe().find('em');
        timer = setTimeout(function () {
            percent += Math.random() * config.enlarge;
            percent = parseFloat(percent.toFixed(1));
            percent = percent > config.size ? config.size : percent;
            $txt.text(percent + '%');
            me.percent = percent;
            $bar.css({width: percent + '%'});
            if (percent >= config.size) {
                $progress.addClass('loading-progress-complete');
                $bar.addClass('loading-progress-bar-blue');
                me.clear();
            } else {
                if (percent >= config.green) {
                    $bar.addClass('loading-progress-bar-green');
                } else if (percent >= config.yellow) {
                    $bar.addClass('loading-progress-bar-yellow');
                } else if (percent >= config.orange) {
                    $bar.addClass('loading-progress-bar-orange');
                }
                if (percent < me.maxPercent) {
                    me.load();
                }
            }
        }, config.speed);
    },
    append: function (percent) {
        if (this.timer) {
            clearTimeout(timer);
        }
        percent += this.maxPercent;
        this.maxPercent = percent > this.config.size ? this.config.size : percent;
        this.load();
        return this;
    },
    clear: function () {
        if (this.timer) {
            clearTimeout(timer);
        }
        this.getMe().remove();
        if (this.callback) {
            this.callback();
        }
    },
    stop: function (callback) {
        this.callback = callback;
        if (this.percent >= this.config.size) {
            this.clear();
        } else {
            this.append(this.config.size);
        }
    }
};
